package com.squareshoot.picCheckin;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TipsListAdapter extends ArrayAdapter<String> {
	
	int layout;
	Context context;
	ArrayList<String> tipsList;
	PhotosDownloader photosDl;
	
	static class ViewHolder{
		ImageView photo;
		TextView tipsText;
		TextView nameAndDate;
	}
	
	public TipsListAdapter(Context context, ArrayList<String> objects,boolean cache) {
		super(context, R.layout.tipsadapter, objects);
		
		this.layout = R.layout.tipsadapter;
		this.context = context;
		this.tipsList = objects;
		photosDl = new PhotosDownloader(cache,true,getContext().getResources().getDrawable(R.drawable.blank_boy));
	}
	
	public View getView(int position,View convertView,ViewGroup parent){
		ViewHolder holder;
		String tip = tipsList.get(position);
		JSONObject jTip;
		
		if(convertView==null){
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView=inflater.inflate(layout, parent, false);
			
			holder = new ViewHolder();
			holder.photo = (ImageView) convertView.findViewById(R.id.tipsPhoto);
			holder.tipsText = (TextView) convertView.findViewById(R.id.tipsText);
			holder.nameAndDate = (TextView) convertView.findViewById(R.id.tipsDateAndName);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder)convertView.getTag();
		}

		try {
			jTip = new JSONObject(tip);
			holder.tipsText.setText(jTip.getString("text"));
			
			JSONObject jUser = jTip.getJSONObject("user");
			photosDl.getPhoto(jUser.getString("photo"),holder.photo);
			String name = jUser.getString("firstname");
			if(jUser.has("lastname"))
				name+=" "+jUser.getString("lastname");
			holder.nameAndDate.setText(name);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		return convertView;
	}
}
